
#include "DirectInput.h"

BOOL CALLBACK DIEnumDevicesCallBack( LPCDIDEVICEINSTANCE lpDdi,LPVOID pvRef)
{
	CDirectInput* pDirectInput = (CDirectInput*) pvRef;

	int iType = GET_DIDEVICE_TYPE( lpDdi->dwDevType) - DI8DEVTYPE_MOUSE;
	
	pDirectInput->devInst[iType].push_back( *lpDdi );
	
	return DIENUM_CONTINUE;
}

CDirectInput::CDirectInput()
{
	m_hWnd = NULL;
}

CDirectInput::~CDirectInput()
{
}

bool CDirectInput::Create(HWND hWnd)
{
	IDirectInput8 * pDI = NULL;

	HINSTANCE hInst = GetModuleHandle(NULL);
	HRESULT hr = DirectInput8Create( hInst,DIRECTINPUT_VERSION,IID_IDirectInput8,(void**)&pDI,NULL );
	
	if(FAILED(hr))
	{
		return false;
	}

	m_hWnd = hWnd;

	m_pDI.Attach( pDI );

	devInst.resize( DI_MaxDeviceType );

	m_pDI->EnumDevices(DI8DEVCLASS_ALL,DIEnumDevicesCallBack,this,DIEDFL_ATTACHEDONLY);

	return true;
}

void CDirectInput::Destroy()
{
	int n = (int) devInst.size();

	for( int i = 0;i<n;i++)
	{
		devInst[i].clear();
	}
	devInst.clear();

	m_pDI.Release();

}

int CDirectInput::GetDeviceInstanceCount( DIDeviceType type )
{
	int nInstance = (int) devInst[type].size();
	return nInstance;
}

LPCDIDEVICEINSTANCE CDirectInput::GetDeviceInstance( DIDeviceType type,int iDevice)
{
	LPCDIDEVICEINSTANCE pDevInst = &devInst[type][iDevice];
	return pDevInst;
}

int CDirectInput::GetMouseInstanceCount()
{
	int nMouseInst = GetDeviceInstanceCount( CDirectInput::DI_Mouse );
	return nMouseInst;
}

LPCDIDEVICEINSTANCE CDirectInput::GetMouseInstance( int iMouse)
{
	return GetDeviceInstance( CDirectInput::DI_Mouse,iMouse );
}

int CDirectInput::GetKeyboardInstanceCount()
{
	return GetDeviceInstanceCount( CDirectInput::DI_Keyboard );
}
LPCDIDEVICEINSTANCE CDirectInput::GetKeyboardInstance( int iKeyboard )
{
	return GetDeviceInstance( CDirectInput::DI_Keyboard,iKeyboard );
}

int CDirectInput::GetJoystickInstanceCount()
{
	return GetDeviceInstanceCount( CDirectInput::DI_Joystick );
}

LPCDIDEVICEINSTANCE CDirectInput::GetJoystickInstance( int iJoystick )
{
	return GetDeviceInstance( CDirectInput::DI_Joystick,iJoystick );
}

LPDIRECTINPUTDEVICE8 CDirectInput::CreateDevice( LPCDIDEVICEINSTANCE pDevInst )
{
	LPDIRECTINPUTDEVICE8 pDIDevice = NULL;
	HRESULT hr = m_pDI->CreateDevice( pDevInst->guidInstance,& pDIDevice, NULL);
	return pDIDevice;
}
